from django.contrib.auth.models import Group
from rest_framework import serializers
from users.models import User


class AdminModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        # exclude = ['default_address', 'email_avtive', 'date_joined']
        fields = ['id', 'username', 'password', 'mobile', 'email', 'groups', 'user_permissions']
        extra_kwargs = {
            "password": {
                "write_only": True
            }
        }

    def create(self, validated_data):
        validated_data["is_staff"] = True
        validated_data["is_superuser"] = True
        user = super().create(validated_data)  # 实现多对多的关联
        user.set_password(validated_data["password"])
        user.save()
        return user

    def update(self, instance, validated_data):
        user = super().update(instance, validated_data)  # 实现多对多的关联
        user.set_password(validated_data["password"])
        user.save()
        return user


class AdminGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ["id", "name"]
